<template>
  <div style="width: 1408px;">
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onDestroyed="handleDestroyed"
        @onFocus="handleFocus"
        @onBlur="handleBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
      />
    </div>
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  nextTick,
  watch,
  reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
  components: { Editor, Toolbar },
  props: {
    modelValue: String,
  },
  emits: ["updateValue"],
  setup(props, context) {
    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref("");
    watch(
      () => props.modelValue,
      () => {
        valueHtml.value = props.modelValue;
      },
      { immediate: true }
    );
    // 模拟 ajax 异步获取内容
    onMounted(() => {
      
    });

    const toolbarConfig = reactive({
      toolbarKeys: [
        'bold', // 加粗
        'italic', // 斜体
        'through', // 删除线
        'underline', // 下划线
        'bulletedList', // 无序列表
        'numberedList', // 有序列表
        'color', // 文字颜色
        'fontSize', // 字体大小
        'lineHeight', // 行高
        'delIndent', // 缩进
        'indent', // 增进
        'divider', // 分割线
        'justifyCenter', // 居中对齐
        'justifyJustify', // 两端对齐
        'justifyLeft', // 左对齐
        'justifyRight', // 右对齐
        'undo', // 撤销
        'redo', // 重做
        'fontFamily', // 字体
        'headerSelect' ,// 标题
        'uploadImage', // 上传图片
        'insertTable', // 插入表格
      ],
      excludeKeys: [
        'bgColor', // 背景色
        'blockquote', // 引用
        'codeBlock', // 代码段
        'emotion', // 表情
        'deleteImage',//删除图片
        'fullScreen', // 全屏
        'insertLink', // 插入链接
        'clearStyle', // 清除格
        'insertImage', // 网络图片
      ]
    })
    // 初始化 MENU_CONF 属性
    const editorConfig = {
      // JS 语法
      MENU_CONF: {},
      placeholder: "请输入内容...",

      // 其他属性...
    };
    
    editorConfig.MENU_CONF["uploadImage"] = {
      server: "/ibem/api/v2/upload/upload.json",
      fieldName: "file",
      meta: {
        type: "INDEX_PIC",
      },
      // 自定义插入图片
      customInsert(res, insertFn) {
        // JS 语法
        // res 即服务端的返回结果
        console.log(res);
        const url = res.value.url;
        const alt = "";
        const href = res.value.url;
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(url, alt, href);
      },
    };
    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    // 编辑器回调函数
    const handleCreated = (editor) => {
      console.log("created", editor);
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
    const handleChange = (editor) => {
      console.log("change:", editor.getHtml());
      context.emit("updateValue", editor.getHtml());
    };
    const handleDestroyed = (editor) => {
      console.log("destroyed", editor);
    };
    const handleFocus = (editor) => {
      console.log("focus", editor);
    };
    const handleBlur = (editor) => {
      context.emit("updateValue", editor.getHtml());
    };
    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`);
    };
    const customPaste = (editor, event, callback) => {
          const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
    const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
    const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

    editor.dangerouslyInsertHtml(html) // 显示编译后的html
 
 // 返回 false ，阻止默认

 event.preventDefault();


    };

    const insertText = () => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.insertText("hello world");
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable();
    };

    return {
      toolbarConfig,
      editorRef,
      mode: "default",
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      handleDestroyed,
      handleFocus,
      handleBlur,
      customAlert,
      customPaste,
      insertText,
      printHtml,
      disable,
    };
  },
};
</script>
